import subprocess
import cv2
from PIL import Image
import numpy as np
import os
def convert_video_to_image_sequence(input_file, output_folder,png_folderName):
    ffmpeg = "H:/RareWolf_Toolkit/Package/ffmpeg/ffmpeg.exe"
    cmd = f"{ffmpeg} -i {input_file} \"{output_folder}/{png_folderName}_%03d.png\""
    subprocess.call(cmd, shell=True)

def RemoveBlackBackground ( input_path: str , file_name: str , output_path: str ) :
    target_im = Image.open ( os.path.join ( input_path , file_name ) )
    target_im = target_im.convert ( 'RGBA' )
    target_img_array = np.array ( target_im )
    # 透明度
    target_img_Alpha = np.max ( target_img_array [ : , : , :3 ] , axis = 2 )
    target_img_array [ : , : , 3 ] = target_img_Alpha
    # 保证在黑色背景上时与原图一致
    target_img_Alpha = target_img_Alpha / 255
    target_img_array [ : , : , :3 ] / target_img_Alpha.reshape ( [ target_img_array.shape [ 0 ] , -1 , 1 ] )
    res_img = Image.fromarray ( target_img_array )
    if not file_name.endswith ( ".png" ) :
        res_img.save ( os.path.join ( output_path , file_name [ :-4 ] + ".png" ) )
    else :
        res_img.save ( os.path.join ( output_path , file_name ) )

input_path  = "D:\BaiduNetdiskDownload\序列素材/339个烟雾粉尘爆炸冲击波特效合成素材-Mov/"
output_folder = "D:\BaiduNetdiskDownload\序列素材/339个烟雾粉尘爆炸冲击波特效合成素材-Png/"
for filename in os.listdir(input_path):
    if filename.endswith ( ".mov" ) or filename.endswith(".mp4") :
        video_input_path = os.path.join(input_path,filename).replace("\\","/")
        print(video_input_path)
        png_folderName= filename.split (".")[0]
        print ( png_folderName )
        png_output_folder = os.path.join(output_folder,png_folderName).replace("\\","/")
        print ( png_output_folder )
        if not os.path.exists ( png_output_folder ) :
            os.mkdir ( png_output_folder )
        convert_video_to_image_sequence ( video_input_path,png_output_folder,png_folderName)


        # 使用RemoveBlackBackground函数将提取的帧转换为带透明通道的PNG
        for filename in os.listdir ( png_output_folder ) :
            if filename.endswith ( ".png" ) :
                RemoveBlackBackground ( png_output_folder , filename , png_output_folder )
        print ( "PNG修改完成" )
